/**
 * AbstractRequester.java
 *
 * @author liujie11
 * 
 * @date 2013-4
 * 
 */
package com.baidu.common.async_http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.baidu.common.utils.AppLog;
import com.japher.hackson.response.BaseResponse;

public abstract class AbstractParser {
    
    public BaseResponse parse(InputStream in) {
        String err = "";
        // try
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte data[] = null;
        int c = 0;
        try {
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            data = out.toByteArray();
            
            String str = new String(data);
            AppLog.debug("res", str);
            
            BaseResponse p = null;
            try {
                p = jsonParse(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            if (p != null)
                return p;
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        BaseResponse r = new BaseResponse();
        r.setStatus(BaseResponse.ERR_CODE_JSON_PARSE);
        r.setStatusMessage(err);
        return r;
    }
    
    protected abstract AbstractParser createParser();
    
    protected abstract BaseResponse jsonParse(String json);
    
}